package org.example.design.rabbit.rpc;

import com.rabbitmq.client.*;
import org.example.design.rabbit.constant.Constants;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;

/**
 * RPC客户端
 */
public class RpcClient {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1.创建连接
        ConnectionFactory connectionFactory=new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.PORT);
        connectionFactory.setUsername(Constants.USER_NAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection=connectionFactory.newConnection();

        //2.开启信道
        Channel channel=connection.createChannel();

        //3.声明队列
        channel.queueDeclare(Constants.RPC_REQUEST_QUEUE,true,false,false,null);
        channel.queueDeclare(Constants.RPC_RESPONSE_QUEUE,true,false,false,null);

        //4.发送请求
        //消息内容
        String msg="hello rpc";
        //设置请求的唯一标识
        String correlationId= UUID.randomUUID().toString();
        //设置相关属性
        AMQP.BasicProperties pros=new AMQP.BasicProperties().builder()
                .correlationId(correlationId)
                .replyTo(Constants.RPC_RESPONSE_QUEUE)
                .build();
        channel.basicPublish("",Constants.RPC_REQUEST_QUEUE,pros,msg.getBytes());

        //5.接收响应
        final BlockingQueue<String> response=new ArrayBlockingQueue<>(1);
        DefaultConsumer consumer=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String respMsg=new String(body);
                System.out.println("接收到消息");
                if(correlationId.equals(properties.getCorrelationId())){
                    response.offer(respMsg);
                }
            }
        };
        channel.basicConsume(Constants.RPC_RESPONSE_QUEUE,true,consumer);
        String result=response.take();
        System.out.println("rpc接收到的信息是："+result);
    }
}